package com.ktvme.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpUtil {

    private static final CloseableHttpClient httpClient = HttpClients.createDefault();

    /**
     * 发送 GET 请求
     *
     * @param url 请求的 URL
     * @param token 认证令牌
     * @return 响应内容
     * @throws IOException 如果请求失败
     */
    public static String sendGetRequest(String url, String token) throws IOException {
        HttpGet request = new HttpGet(url);
        request.setHeader("token", token);
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity);
            }
        }
        return null;
    }

    /**
     * 发送 GET 请求，带参数
     *
     * @param url 请求的 URL
     * @param params 请求参数
     * @param token 认证令牌
     * @return 响应内容
     * @throws IOException 如果请求失败
     */
    public static String sendGetRequest(String url, Map<String, String> params, String token) throws IOException {
        if (params != null && !params.isEmpty()) {
            StringBuilder paramBuilder = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (paramBuilder.length() > 0) {
                    paramBuilder.append("&");
                }
                paramBuilder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString()));
            }
            url += "?" + paramBuilder.toString();
        }

        HttpGet request = new HttpGet(url);
        request.setHeader("token", token);
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity) : null;
        }
    }

    /**
     * 发送 POST 请求
     *
     * @param url 请求的 URL
     * @param body 请求体内容
     * @param token 认证令牌
     * @return 响应内容
     * @throws IOException 如果请求失败
     */
    public static String sendPostRequest(String url, String body, String token) throws IOException {
        HttpPost request = new HttpPost(url);
        request.setHeader("token", token);
        request.setEntity(new StringEntity(body));
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity);
            }
        }
        return null;
    }

    /**
     * 发送 DELETE 请求
     *
     * @param url 请求的 URL
     * @param token 认证令牌
     * @return 响应内容
     * @throws IOException 如果请求失败
     */
    public static String sendDeleteRequest(String url, String token) throws IOException {
        HttpDelete request = new HttpDelete(url);
        request.setHeader("token", token);
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity);
            }
        }
        return null;
    }

    public static String sendPostRequestWithParams(String url, Map<String, String> params, String token) throws IOException {
        if (params != null && !params.isEmpty()) {
            StringBuilder paramBuilder = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (paramBuilder.length() > 0) {
                    paramBuilder.append("&");
                }
                paramBuilder.append(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()));
                paramBuilder.append("=");
                paramBuilder.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString()));
            }
            // 检查URL是否已经包含了查询字符串
            if (!url.contains("?")) {
                url += "?";
            } else if (!url.endsWith("?") && !url.endsWith("&")) {
                url += "&";
            }
            url += paramBuilder.toString();
        }

        HttpPost request = new HttpPost(url);
        request.setHeader("token", token);
        try (CloseableHttpResponse response = httpClient.execute(request)) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity) : null;
        }
    }
}
